package com.example.myapplication1.ui.cart;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.example.myapplication1.R;
import com.example.myapplication1.db.OrderManager;
import com.example.myapplication1.utils.PreferenceManager;
import com.example.myapplication1.db.DatabaseHelper;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

public class CartFragment extends Fragment {
    private TextView catFoodQuantity;
    private TextView freezeDriedQuantity;
    private TextView catTreatsQuantity;
    private TextView totalPriceText;
    private Button submitOrderButton;
    
    private int catFoodCount = 0;
    private int freezeDriedCount = 0;
    private int catTreatsCount = 0;
    
    private static final double CAT_FOOD_PRICE = 0.20;
    private static final double FREEZE_DRIED_PRICE = 0.30;
    private static final double CAT_TREATS_PRICE = 0.50;
    
    private OrderManager orderManager;
    private PreferenceManager preferenceManager;
    private DatabaseHelper databaseHelper;
    private double totalPrice = 0.0;





    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_cart, container, false);
        
        // 初始化管理器
        orderManager = new OrderManager(requireContext());
        preferenceManager = new PreferenceManager(requireContext());
        databaseHelper = new DatabaseHelper(requireContext());
        
        // Initialize views
        catFoodQuantity = view.findViewById(R.id.cat_food_quantity);
        freezeDriedQuantity = view.findViewById(R.id.freeze_dried_quantity);
        catTreatsQuantity = view.findViewById(R.id.cat_treats_quantity);
        totalPriceText = view.findViewById(R.id.total_price);
        submitOrderButton = view.findViewById(R.id.submit_order);
        
        // Set up cat food controls
        ImageButton catFoodAdd = view.findViewById(R.id.cat_food_add);
        ImageButton catFoodMinus = view.findViewById(R.id.cat_food_minus);
        
        catFoodAdd.setOnClickListener(v -> updateQuantity(true, 0));
        catFoodMinus.setOnClickListener(v -> updateQuantity(false, 0));
        
        // Set up freeze dried controls
        ImageButton freezeDriedAdd = view.findViewById(R.id.freeze_dried_add);
        ImageButton freezeDriedMinus = view.findViewById(R.id.freeze_dried_minus);
        
        freezeDriedAdd.setOnClickListener(v -> updateQuantity(true, 1));
        freezeDriedMinus.setOnClickListener(v -> updateQuantity(false, 1));
        
        // Set up cat treats controls
        ImageButton catTreatsAdd = view.findViewById(R.id.cat_treats_add);
        ImageButton catTreatsMinus = view.findViewById(R.id.cat_treats_minus);
        
        catTreatsAdd.setOnClickListener(v -> updateQuantity(true, 2));
        catTreatsMinus.setOnClickListener(v -> updateQuantity(false, 2));
        
        // Set up submit order button
        submitOrderButton.setOnClickListener(v -> showPaymentConfirmDialog());
        
        updateTotalPrice();
        return view;
    }
    
    private void updateQuantity(boolean isAdd, int productType) {
        switch (productType) {
            case 0: // Cat Food
                catFoodCount = updateCount(catFoodCount, isAdd);
                catFoodQuantity.setText(String.valueOf(catFoodCount));
                Toast.makeText(requireContext(), 
                    isAdd ? "已添加营养猫粮" : "已减少营养猫粮", 
                    Toast.LENGTH_SHORT).show();
                break;
            case 1: // Freeze Dried
                freezeDriedCount = updateCount(freezeDriedCount, isAdd);
                freezeDriedQuantity.setText(String.valueOf(freezeDriedCount));
                Toast.makeText(requireContext(), 
                    isAdd ? "已添加小猫冻干" : "已减少小猫冻干", 
                    Toast.LENGTH_SHORT).show();
                break;
            case 2: // Cat Treats
                catTreatsCount = updateCount(catTreatsCount, isAdd);
                catTreatsQuantity.setText(String.valueOf(catTreatsCount));
                Toast.makeText(requireContext(), 
                    isAdd ? "已添加营养猫条" : "已减少营养猫条", 
                    Toast.LENGTH_SHORT).show();
                break;
        }
        updateTotalPrice();
    }
    
    private int updateCount(int currentCount, boolean isAdd) {
        if (isAdd) {
            return currentCount + 1;
        } else {
            return Math.max(0, currentCount - 1);
        }
    }
    
    private void updateTotalPrice() {
        totalPrice = (catFoodCount * CAT_FOOD_PRICE) +
                    (freezeDriedCount * FREEZE_DRIED_PRICE) +
                    (catTreatsCount * CAT_TREATS_PRICE);
        
        DecimalFormat df = new DecimalFormat("0.00");
        totalPriceText.setText("总计: ¥ " + df.format(totalPrice));
        
        // 根据是否有商品启用或禁用提交按钮
        submitOrderButton.setEnabled(totalPrice > 0);
    }
    
    private void showPaymentConfirmDialog() {
        final Dialog dialog = new Dialog(requireContext());
        dialog.setContentView(R.layout.dialog_payment_confirm);
        
        TextView orderDetailsView = dialog.findViewById(R.id.order_details);
        TextView totalAmountView = dialog.findViewById(R.id.total_amount);
        Button cancelButton = dialog.findViewById(R.id.btn_cancel);
        Button confirmButton = dialog.findViewById(R.id.btn_confirm);
        
        // 获取用户余额
        long userId = preferenceManager.getUserId();
        double userBalance = databaseHelper.getUserBalance(userId);
        
        // 设置订单详情
        StringBuilder details = new StringBuilder();
        if (catFoodCount > 0) {
            details.append("营养猫粮: ").append(catFoodCount).append("份 x ¥").append(CAT_FOOD_PRICE).append("\n");
        }
        if (freezeDriedCount > 0) {
            details.append("小猫冻干: ").append(freezeDriedCount).append("份 x ¥").append(FREEZE_DRIED_PRICE).append("\n");
        }
        if (catTreatsCount > 0) {
            details.append("营养猫条: ").append(catTreatsCount).append("份 x ¥").append(CAT_TREATS_PRICE).append("\n");
        }
        details.append("\n当前余额: ¥").append(String.format("%.2f", userBalance));
        
        orderDetailsView.setText(details.toString());
        totalAmountView.setText(String.format("需支付: ¥ %.2f", totalPrice));
        
        // 设置按钮点击事件
        cancelButton.setOnClickListener(v -> dialog.dismiss());
        confirmButton.setOnClickListener(v -> {
            processOrder();
            dialog.dismiss();
        });
        
        dialog.show();
    }
    
    private void processOrder() {
        // 获取用户ID和余额
        long userId = preferenceManager.getUserId();
        double userBalance = databaseHelper.getUserBalance(userId);

        // 检查余额是否足够
        if (userBalance < totalPrice) {
            Toast.makeText(requireContext(), 
                "余额不足，当前余额: ¥" + String.format("%.2f", userBalance) + "\n请充值后再试", 
                Toast.LENGTH_LONG).show();
            return;
        }

        // 准备订单项
        List<OrderManager.OrderItem> items = new ArrayList<>();
        
        if (catFoodCount > 0) {
            items.add(new OrderManager.OrderItem("营养猫粮", catFoodCount, CAT_FOOD_PRICE, "商店"));
        }
        if (freezeDriedCount > 0) {
            items.add(new OrderManager.OrderItem("小猫冻干", freezeDriedCount, FREEZE_DRIED_PRICE, "商店"));
        }
        if (catTreatsCount > 0) {
            items.add(new OrderManager.OrderItem("营养猫条", catTreatsCount, CAT_TREATS_PRICE, "商店"));
        }
        
        // 创建订单
        long orderId = orderManager.createOrder(
            userId,
            totalPrice,
            items.toArray(new OrderManager.OrderItem[0])
        );
        
        if (orderId != -1) {
            // 更新用户余额
            double newBalance = userBalance - totalPrice;
            if (databaseHelper.updateUserBalance(userId, newBalance)) {
                // 更新SharedPreferences中的余额
                preferenceManager.setBalance(newBalance);
                
                // 发送广播通知ProfileFragment更新余额
                Intent intent = new Intent("balance_updated");
                LocalBroadcastManager.getInstance(requireContext()).sendBroadcast(intent);
                
                // 订单创建成功
                Toast.makeText(requireContext(), 
                    "支付成功！\n当前余额: ¥" + String.format("%.2f", newBalance), 
                    Toast.LENGTH_SHORT).show();
                
                // 重置购物车
                catFoodCount = 0;
                freezeDriedCount = 0;
                catTreatsCount = 0;
                
                catFoodQuantity.setText("0");
                freezeDriedQuantity.setText("0");
                catTreatsQuantity.setText("0");
                
                updateTotalPrice();
            } else {
                Toast.makeText(requireContext(), "支付失败，请重试", Toast.LENGTH_SHORT).show();
            }
        } else {
            // 订单创建失败
            Toast.makeText(requireContext(), "支付失败，请重试", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (databaseHelper != null) {
            databaseHelper.close();
        }
    }
} 